package com.shujia.day14;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo08ThreadPool {
    public static void main(String[] args) throws InterruptedException {
//        ExecutorService executorService = Executors.newCachedThreadPool();
//        executorService.submit(new MyThreadRunnable());  // 当线程池中给定了线程对象那么就可以执行线程
//
//        Thread.sleep(3 * 1000);
//
//        executorService.shutdownNow();  // 可以通过shutdown关闭当前线程池
//        executorService.shutdown();

        // TODO 当线程池中给定了固定的线程数，那么只能运行指定数量线程，当该部分线程执行完成后，再执行其他线程
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(new MyThreadRunnable());
//        executorService.submit(new MyThreadRunnable());
//        executorService.submit(new MyThreadRunnable());
//        executorService.submit(new MyThreadRunnable());

        // 线程池的作用是对当前的线程进行控制


        /*
            TODO Callable方式构建多线程的对象
                相比较其他方式， Callable中的call方法就相当于是run方法
                但是call方法有一个返回值  可以给定任意的引用类型 比如集合类
         */
        executorService.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                System.out.println("当前是由Callable提供的call方法");
                return null;
            }
        });


    }

    static class MyThreadRunnable implements Runnable{

//        @Override
//        public void run() {
//            while (true){
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                System.out.println("当前runnable正在运行。。。。");
//            }
//        }


        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() +"当前线程正在执行.."+i);
            }
        }
    }
}
